<template>
  <div>
    <div>
      <el-form>
        <el-col :span="10">
          <el-form-item label="收费名称">
            <el-input v-model="queryParams.name" clearable style="width: 350px" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-plus" @click="insertCost">添加</el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            v-hasPermi="['community:cost:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="deleteCost"
          >删除</el-button>
        </el-col>
      </el-form>
    </div>
    <div>
      <el-table
        v-loading="loading"
        :data="costs"
        border
        stripe
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
      > align="center"
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="名称" prop="name" align="center" />
        <el-table-column label="收费方式" align="center">
          <template slot-scope="scope">
            {{ scope.row.typeId | typeFilter }}
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center">
          <template slot-scope="scope">
            {{ scope.row.unitprice + "元 / " }}{{ scope.row.typeId | typeUnitFilter }}
          </template>
        </el-table-column>
        <el-table-column label="收费频率" align="center">
          <template slot-scope="scope">
            {{ scope.row.frequency | frequencyFilter }}
          </template>
        </el-table-column>
        <el-table-column v-if="type === 'timing'" label="收费日期" prop="time" align="center">
          <template slot-scope="scope">
            {{ scope.row.startTime | dataFormatFilter }}
          </template>
        </el-table-column>
        <el-table-column v-if="type === 'timing'" label="结束日期" prop="time" align="center">
          <template slot-scope="scope">
            {{ scope.row.endTime | dataFormatFilter }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success">
              {{ scope.row.status | statusFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="type === 'timing'" label="是否启用" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="500" align="center">
          <template slot-scope="scope">
            <div style="display: flex;justify-content: center">
              <el-button
                v-if="scope.row.status === 1 || scope.row.status === 2"
                type="primary"
                @click="startCharge(scope.row)"
              >发起</el-button>
              <el-button
                v-if="scope.row.status === 0"
                type="primary"
                @click="stopCharging(scope.row)"
              >结束</el-button>
              <el-button
                type="success"
                @click="payDetail(scope.row.id, scope.row.name)"
              >详情</el-button>
              <el-button
                type="info"
                @click="updateCost(scope.row)"
              >修改</el-button>
              <el-button
                type="danger"
                @click="deleteCost(scope.row)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--   分页   -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getCosts"
    />
    <!--  添加 或 修改 对话框  -->
    <el-dialog
      :title="editType === 'insert' ? '添加收费条目' : '修改收费条目'"
      :visible.sync="editDialog"
      width="50%"
      :before-close="closeDialog"
      style="font-weight: bold"
    >
      <el-form :model="tmpCost" label-width="120px">
        <el-form-item label="收费名称">
          <el-input v-model="tmpCost.name" clearable class="dialog-input" />
        </el-form-item>
        <el-form-item label="收费方式">
          <el-select
            v-model="tmpCost.typeId"
            filterable
            allow-create
          >
            <el-option
              v-for="item in typeArray"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              filterable
              allow-create
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="tmpCost.unitprice" class="dialog-input">
            <template slot="append">元 / {{ tmpCost.typeId | typeUnitFilter }}</template>
          </el-input>
        </el-form-item>
        <!--        <el-form-item label="收费频率">
          <el-select
            v-model="tmpCost.frequency"
            filterable
            allow-create
          >
            <el-option
              v-for="item in frequencyArray"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>-->
        <!--        <el-form-item label="收费持续时间">
          <el-input v-model="tmpCost.limit" clearable style="width: 150px">
            <span slot="append">天</span>
          </el-input>
        </el-form-item>-->
        <el-form-item v-if="this.tmpCost.frequency === 1" label="执行日期">
          <el-date-picker
            v-model="tmpCost.time"
            type="date"
            format=" MM 月 dd 日"
            value-format=" MM 月 dd 日"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item v-if="this.tmpCost.frequency === 2" label="执行日期">
          <el-date-picker
            v-model="tmpCost.time"
            type="date"
            format=" dd 日"
            value-format=" dd 日"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item v-if="this.tmpCost.frequency !== 0" label="立即启用">
          <el-switch v-model="tmpCost.enable" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitCost">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 发起收费对话框 -->
    <el-dialog
      :title="chargeCost.name"
      :visible.sync="chargeDialog"
      close-on-click-modal="false"
      width="50%"
      :before-close="closeCharge"
      style="font-weight: bold"
    >
      <div class="dialog-body">
        <el-form>
          <el-form-item label="请选择缴费户:" label-width="130px">
            <el-tree
              ref="groupTree"
              :data="group"
              show-checkbox
              node-key="deptId"
              highlight-current
              :props="customProps"
              :default-checked-keys="defaultChecked"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="closeCharge">取 消</el-button>
        <el-button type="primary" @click="submitCharge">确 定</el-button>
      </span>
    </el-dialog>
  </div></template>

<script>
import { originalCosts, baseGroup } from '/src/utils/baseInfo'
import { listDept } from "../../api/system/dept";
import { listCost, addCost, updateCost, delCost, startCharge, stopCharge } from '../../api/pay/cost'
import { getHisIdByCostId } from "../../api/pay/history"

const typeArray = [
  {
    value: 1,
    label: '按户'
  },
  {
    value: 2,
    label: '房屋面积'
  },
  {
    value: 3,
    label: '人口'
  },
  {
    value: 4,
    label: '体积'
  },
  {
    value: 5,
    label: '度数'
  }
]

const typeUnitArray = [
  '户',
  '平方米',
  '人',
  '立方米',
  '度'
]

const frequencyArray = [
  {
    value: 0,
    label: '一次性收费'
  },
  {
    value: 1,
    label: '每年一次'
  },
  {
    value: 2,
    label: '每月一次'
  }
]

const statusArray = [
  '收费中',
  '未收费',
  '已完成'
]
export default {
  name: 'CostTable',
  filters: {
    typeFilter(val) {
      return typeArray[val - 1].label
    },
    typeUnitFilter(val) {
      return typeUnitArray[val - 1]
    },
    frequencyFilter(val) {
      return frequencyArray[val].label
    },
    statusFilter(val) {
      return statusArray[val]
    },
    dataFormatFilter(timestamp) {
      const a = new Date(timestamp).getTime()
      const date = new Date(a)
      const month = (date.getMonth() + 1).toString()
      const day = date.getDate().toString()
      return month + ' 月' + day + ' 日'
    }
  },
  props: {
    type: String
  },
  data() {
    return {
      loading: false,
      costs: [],
      isAdvancedSearch: false,
      name: undefined,
      editDialog: false,
      editType: '',
      // 添加或修改的临时数据
      tmpCost: {
        id: '',
        name: '',
        typeId: 1,
        unitprice: undefined,
        frequency: 0,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        enable: true
      },
      typeArray,
      frequencyArray,
      // 发起收费 字段
      chargeDialog: false,
      chargeCost: {
        id: undefined,
        name: '发起收费',
        typeId: undefined,
        unitprice: undefined
      },
      group: [],
      customProps: {
        children: 'children',
        label: 'deptName'
      },
      // 默认勾选的数组
      defaultChecked: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        selectType: 'manual'
      },
      // 查询结果条数
      total: 0,
      // 列表类型
      // eslint-disable-next-line vue/no-dupe-keys
      type: '',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true
    }
  },
  watch: {
    type: {
      handler(newType) {
        // eslint-disable-next-line vue/no-mutating-props
        this.type = newType
        this.queryParams.selectType = newType
        this.getCosts()
      },
      immediate: true
    }
  },
  methods: {
    getCosts() {
      this.loading = true
      listCost(this.queryParams).then(res => {
        console.log(this.queryParams.selectType)
        this.costs = res.rows
        console.log(this.costs)
        this.total = res.total
        this.loading = false
      })
    },
    search() {
      this.queryParams.pageNum = 1
      this.getCosts()
    },
    // 通过 costId 结束
    stopCharging(cost) {
      this.$confirm('您确定要截止【' + cost.name + '】收取吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 截止收费，将状态收费中改成已完成
        stopCharge(cost.id).then(res => {
          // 截止收费后调转到详情页面
          this.payDetail(cost.id, cost.name)
          this.$message.success('已结束收费，调转到详情页面！')
        })
      }).catch(() => {
        this.$message.info('已取消截止收费')
      })
    },
    // 删除多选操作
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 删除收费项
    deleteCost(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除缴费设置编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCost(ids)
      }).then(() => {
        this.getCosts()
        this.msgSuccess('删除成功')
      })
    },
    // 跳转到缴费详情页面，传递 costItemId 查询这条缴费关联的人
    payDetail(costItemId, name) {
      // 先根据costItemId查询出hisId, 之后调优可以 在 detail 页面做判断是 hisId 还是 costId
      getHisIdByCostId(costItemId).then(res => {
        this.$router.push({
          path: 'paydetail',
          query: {
            hisId: res.data,
            name
          }
        })
      })
    },
    // 修改或删除的函数
    insertCost() {
      this.editDialog = true
      this.editType = 'insert'
      if (this.type === 'manual') {
        this.tmpCost.frequency = 0
      } else {
        this.tmpCost.frequency = 1
      }
    },
    submitCost() {
      if (this.editType === 'insert') {
        // 0 收费中 1 未收费 2 已完成（定时收费已完成本年度、季度的收费）
        this.tmpCost.status = 1
        // 发送新增请求
        addCost(this.tmpCost).then(res => {
          this.msgSuccess('新增成功')
          this.getCosts()
        })
      } else {
        // 修改
        updateCost(this.tmpCost).then(res => {
          this.msgSuccess('修改成功')
          this.getCosts()
        })
      }
      this.closeDialog()
    },
    closeDialog() {
      this.editDialog = false
      this.tmpCost = {
        id: '',
        name: '',
        typeId: 1,
        unitprice: undefined,
        frequency: 0,
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        enable: true
      }
    },
    updateCost(cost) {
      this.tmpCost = cost
      this.editType = 'update'
      this.editDialog = true
    },
    // 发起收费
    startCharge(cost) {
      this.chargeDialog = true
      this.chargeCost = {
        id: cost.id,
        name: cost.name,
        typeId: cost.typeId,
        unitprice: cost.unitprice
      }
      // 获取房间列表
      listDept({
        // 0：是住址和部门公共的结构，1:部门，2：住址，3:房间叶子结点
        type: '2'
      }).then(res => {
        console.log(res.data)
        this.group = this.handleTree(res.data, 'deptId')
        console.log(this.group)
      })
      // 设置默认选中 --- 之后在写
      /*if (cost.defaultFamily === undefined) {
        this.defaultChecked = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 2, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
      } else {
        this.defaultChecked = cost.defaultFamily
      }*/
    },
    closeCharge() {
      this.chargeDialog = false
      this.chargeCost = {
        id: undefined,
        name: '发起收费',
        typeId: '',
        unitprice: undefined
      }
    },
    submitCharge() {
      this.$refs.groupTree.getCheckedNodes()
      const param = {
        costId: this.chargeCost.id,
        typeId: this.chargeCost.typeId,
        //  过滤只获取房间节点, 在映射为 deptId数组
        deptIds: this.$refs.groupTree.getCheckedNodes().filter(item => item.type === '3').map(item => item.deptId),
        unitprice: this.chargeCost.unitprice
      }
      console.log(param)
      startCharge(param).then(res => {
        this.msgSuccess(res.msg)
      })
      this.closeCharge()
    }
  }
}
</script>

<style>
  .dialog-input {
    width: 400px;
  }
  .dialog-body {
    font-weight: normal;
  }
</style>
